import * as util from 'util';

import { DB } from './DB';
import { Column, Table } from '../model/schema';


export class QuerySchema {
    dbType: string;
    tablesSql: string;
    tableFieldsSql: string;
    tableName: string;
    tableComment: string;
    fieldName: string;
    fieldType: string;
    fieldComment: string;
    fieldKey: string;
    fieldDefaultValue: any;

    constructor(dbType: string){
        this.dbType = dbType;
    }

    init(tablesSql, tableCommentsSql, tableFieldsSql,
        tableName, tableComment, fieldName, fieldType,
        fieldComment, fieldKey, fieldDefaultValue) {
        
        this.tablesSql = tablesSql;
        this.tableFieldsSql = tableFieldsSql;
        this.tableName = tableName;
        this.tableComment = tableComment;
        this.fieldName = fieldName;
        this.fieldType = fieldType;
        this.fieldComment = fieldComment;
        this.fieldKey = fieldKey;
        this.fieldDefaultValue = fieldDefaultValue;
    }
    parseTableFromDB(tableItem: any){
        // subclass implements
        return null;
    }

    parseColumnFromDB(fieldItem: any){
        // subclass implements
        return null;
    }

    async getTables(db: DB) {
        let that = this;
        let getFields = async function (table) {
            let tableFieldsSql = util.format(that.tableFieldsSql, table.name);
            let [fields,] = await db.query(tableFieldsSql);
            let columns : Column[] = [];
            for (let fieldItem of fields) {
                columns.push(db.schema.parseColumnFromDB(fieldItem));
            }
            return columns;
        };

        let [tableInfos,] = await db.query(this.tablesSql);
        let tables = [];
        for (let item of tableInfos) {
            let table : Table = db.schema.parseTableFromDB(item);
            table.setColumns(await getFields(table));
            tables.push(table);
        }
        return tables;
    };
}